<template>
  <div class="trend-chart">
    <h3 class="chart-title">{{ title }}</h3>

    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="5" animated />
    </div>

    <div v-else-if="!chartData || chartData.length === 0" class="no-data">
      <el-empty description="暂无数据" />
    </div>

    <div v-else class="chart-container">
      <v-chart
        :option="chartOption"
        :style="{ height: '350px', width: '100%' }"
        autoresize
      />
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { LineChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
  DataZoomComponent
} from 'echarts/components'
import VChart from 'vue-echarts'
import { analyticsApi } from '@/api/analytics'
import dayjs from 'dayjs'

// 注册ECharts组件
use([
  CanvasRenderer,
  LineChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
  DataZoomComponent
])

const props = defineProps({
  title: {
    type: String,
    required: true
  },
  type: {
    type: String,
    required: true,
    validator: (value) => ['startTime', 'completion'].includes(value)
  },
  studentId: {
    type: Number,
    required: true
  }
})

const loading = ref(false)
const chartData = ref([])

// 将分钟数转换为时间格式字符串
const formatMinutesToTime = (minutes) => {
  const hours = Math.floor(minutes / 60)
  const mins = Math.floor(minutes % 60)
  return `${hours.toString().padStart(2, '0')}:${mins.toString().padStart(2, '0')}`
}

// 根据类型获取图表数据
const loadChartData = async () => {
  if (!props.studentId) return

  try {
    loading.value = true

    let response
    if (props.type === 'startTime') {
      response = await analyticsApi.getStartTimeTrend(props.studentId)
    } else {
      response = await analyticsApi.getCompletionTimeTrend(props.studentId)
    }

    chartData.value = response.data || []

    console.log(`📊 ${props.type === 'startTime' ? '开始时间' : '完成时间'}数据:`, chartData.value)
  } catch (error) {
    console.error('加载图表数据失败:', error)
    chartData.value = []
  } finally {
    loading.value = false
  }
}

// 获取最早时间点（适配新的数据格式）
const getEarliestTime = (data, date) => {
  const item = data.find(d => d.date === date)
  return item ? item.earliest_time_minutes : null
}

// ECharts配置选项 - 单一趋势线
const chartOption = computed(() => {
  if (!chartData.value || chartData.value.length === 0) {
    return {}
  }

  // 处理数据
  const dates = [...new Set(chartData.value.map(item => item.date))].sort()

  // 为每个日期创建最早时间点数据
  const timeData = dates.map(date => {
    const item = chartData.value.find(d => d.date === date)
    return item ? item.earliest_time_minutes : null
  })

  // 创建单一数据系列
  const series = [{
    name: props.type === 'startTime' ? '最早开始时间' : '最早完成时间',
    type: 'line',
    smooth: true,
    symbol: 'circle',
    symbolSize: 8,
    data: timeData,
    emphasis: {
      focus: 'series'
    },
    lineStyle: {
      width: 3
    },
    itemStyle: {
      color: props.type === 'startTime' ? '#5470c6' : '#91cc75'
    }
  }]

  return {
    title: {
      show: false
    },
    tooltip: {
      trigger: 'axis',
      formatter: (params) => {
        const param = params[0]
        if (param.value === null || param.value === undefined) {
          return `${param.axisValueLabel}<br/>暂无数据`
        }
        const timeStr = formatMinutesToTime(param.value)
        return `${param.axisValueLabel}<br/>${param.marker}${param.seriesName}: ${timeStr}`
      }
    },
    legend: {
      data: series.map(s => s.name),
      top: 10
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: dates.map(date => dayjs(date).format('MM-DD')),
      axisLabel: {
        rotate: 45
      }
    },
    yAxis: {
      type: 'value',
      name: '时间',
      min: 0,
      max: 24 * 60, // 24小时 * 60分钟
      axisLabel: {
        formatter: (value) => formatMinutesToTime(value)
      }
    },
    dataZoom: [
      {
        type: 'inside',
        start: 0,
        end: 100
      },
      {
        start: 0,
        end: 100,
        height: 20,
        bottom: 10
      }
    ],
    series: series
  }
})

// 监听学生ID变化
watch(() => props.studentId, () => {
  if (props.studentId) {
    loadChartData()
  }
}, { immediate: true })
</script>

<style scoped>
.trend-chart {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.chart-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 20px;
  color: #333;
  text-align: center;
}

.loading-container {
  padding: 20px;
}

.no-data {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 350px;
}

.chart-container {
  width: 100%;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .trend-chart {
    padding: 12px;
  }

  .chart-title {
    font-size: 16px;
    margin-bottom: 16px;
  }

  .no-data {
    height: 300px;
  }
}

@media (max-width: 480px) {
  .trend-chart {
    padding: 8px;
  }

  .chart-title {
    font-size: 14px;
    margin-bottom: 12px;
  }
}
</style>